package com.ybl.store.backend.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ybl.store.backend.dao.entity.customer.CustomerProductDO;
import com.ybl.store.backend.dao.mapper.customer.CustomerProductMapper;
import com.ybl.store.common.convention.errorcode.BaseErrorCode;
import com.ybl.store.common.convention.exception.ClientException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CustomerProductService {

    private final CustomerProductMapper customerProductMapper;

    public void addNumber(Long customerId, Long productId, Integer number) {
        CustomerProductDO customerProductDO = get(customerId, productId);
        customerProductDO.setNumber(customerProductDO.getNumber() + number);
        int result = customerProductMapper.updateById(customerProductDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CUSTOMER_GOOD_ERROR);
        }
    }

    public void subNumber(Long customerId, Long productId, Integer number) {
        CustomerProductDO customerProductDO = get(customerId, productId);
        customerProductDO.setNumber(customerProductDO.getNumber() - number);
        int result = customerProductMapper.updateById(customerProductDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CUSTOMER_GOOD_ERROR);
        }
    }

    private CustomerProductDO get(Long customerId, Long productId) {
        LambdaQueryWrapper<CustomerProductDO> lambdaQueryWrapper = Wrappers.lambdaQuery(CustomerProductDO.class)
                .eq(CustomerProductDO::getCustomerId, customerId)
                .eq(CustomerProductDO::getProductId, productId);
        CustomerProductDO customerProductDO = customerProductMapper.selectOne(lambdaQueryWrapper);
        if (customerProductDO == null) {
            customerProductDO = new CustomerProductDO();
            customerProductDO.setCustomerId(customerId);
            customerProductDO.setProductId(productId);
            customerProductDO.setNumber(0);
            int result = customerProductMapper.insert(customerProductDO);
            if (result < 1) {
                throw new ClientException(BaseErrorCode.CUSTOMER_GOOD_ERROR);
            }
        }
        return customerProductDO;
    }
}
